package com.nf.health.app.inquiry.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lling.photopicker.utils.ImageLoader;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.PhotoPickerActivity;
import com.nf.health.app.activity.global.PictureActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.customview.SquareLayout;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.http.ImageUpLoader;
import com.nf.health.app.inquiry.bean.PatientUser;
import com.nf.health.app.models.Score;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.DateUtil;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.GetToast;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.NetUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 快速问诊
 */
public class FastInquiryActivity extends BaseActivity {

    TextView time_zhong;

    AlertDialog dialog;

    private static final int REQUEST_CODE = 99;
    private static final int PICK_PHOTO = 999;
    private static final String FLAT_FAST_INQUIRY = "fastInquiry";
    private static final String REQUEST_MY_SCORE = "request_my_score";
    private static final String REDUCE_MY_SCORE = "reduce_my_score";
    @Bind(R.id.iv_icon)
    ImageView ivIcon;
    @Bind(R.id.tv_inquiry_key)
    TextView tvInquiryKey;
    @Bind(R.id.rl_patient_user)
    RelativeLayout rlPatientUser;
    @Bind(R.id.et_question_content)
    EditText etQuestionContent;
    @Bind(R.id.grid_view_image)
    GridView gridViewImage;
    @Bind(R.id.tv_add_picture)
    TextView tvAddPicture;
    @Bind(R.id.btn_commit)
    Button btnCommit;
    @Bind(R.id.btn_commit2)
    Button btnCommit2;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;

    private boolean showCamera = true;
    private int selectedMode = PhotoPickerActivity.MODE_MULTI;
    private int maxNum = 5;

    int age;

    Score score;


    private ArrayList<String> mPhotos = new ArrayList<>();
    /**
     * 存储选中的所有图片，本地地址
     */
    private ArrayList<String> allUrls = new ArrayList<>();

    /**
     * 存储上传失败的图片，本地地址
     */
    private ArrayList<String> imgFailureURLs = new ArrayList<>();
    /**
     * 存储上传成功的图片，网络地址
     */
    private ArrayList<String> imgSuccessURLs = new ArrayList<>();
    ThumbPicAdapter thumbPicAdapter;

    private boolean isDel = false;
    String userDesc;
    ImageUpLoader upLoader;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_fast_inquiry);
        ButterKnife.bind(this);
        initView();
        initListener();
    }

    private void initListener() {
        rlPatientUser.setOnClickListener(this);
        tvAddPicture.setOnClickListener(this);
        btnCommit.setOnClickListener(this);
        btnCommit2.setOnClickListener(this);
        titlebarRightView.setOnClickListener(this);
        gridViewImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == mPhotos.size()) {
                    addPicture();
                } else {
                    if (isDel) {
                        return;
                    }
                    //浏览大图
                    Intent intent = new Intent(FastInquiryActivity.this, PictureActivity.class);
                    intent.putExtra(PictureActivity.EXTRA_TYPE, PictureActivity.TYPE_LOCAL_IMG);
                    intent.putExtra(PictureActivity.EXTRA_POSITION, position);
                    intent.putStringArrayListExtra(PictureActivity.EXTRA_IMG_LIST, mPhotos);
                    startActivity(intent);
                }
            }
        });

        gridViewImage.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                isDel = true;
                thumbPicAdapter.setIsDel(isDel);
                thumbPicAdapter.notifyDataSetChanged();
                return false;
            }
        });
    }

    private void initView() {
        ViewUtil.setText(this, R.id.titlebar_title_tv, "快速问诊");
        //默认用户作为问诊人
        String nick_name = PreferenceHelper.getString(PreferenceHelper.USERRNAME, "");
        if(TextUtils.isEmpty(nick_name)){
            nick_name =  PreferenceHelper.getString(PreferenceHelper.USERNICK, "");
        }
        String sex = PreferenceHelper.getString(PreferenceHelper.USERSEX, "");
        String birthday = PreferenceHelper.getString(PreferenceHelper.BIRTHDAY, "");
        //添加的问诊人
        PatientUser user = DbManager.getInstance().getPatientUser();
        if (TextUtils.isEmpty(nick_name + sex + birthday) && user != null) {
            //没有默认问诊人显示添加的问诊人
            setPatientUI(user);
        } else {

            if (TextUtils.isEmpty(birthday)) {

            } else {
                if (!birthday.contains("-")) {//经测试，有些是原来的数据竟然是yyyyMMdd的格式
                    birthday = DateUtil.stringToString("20160425", "yyyyMMdd", "yyyy-MM-dd");
                }
                int year = Integer.parseInt(birthday.split("-")[0]);
                age = Calendar.getInstance().get(Calendar.YEAR) - year;
            }

            if (sex.equals("2")) {
                sex = "女";
                ivIcon.setImageResource(R.drawable.ic_gender_female);
            } else {
                ivIcon.setImageResource(R.drawable.ic_gender_male);
                sex = "男";
            }
            userDesc = nick_name + "," + sex + "," + age + "岁";
            tvInquiryKey.setText("问诊人："+nick_name + " " + sex + " " + age + "岁");
        }
        titlebarRightView.setImageResource(R.drawable.fast_inquiry_icon);
    }


    @Override
    public void onBackPressed() {
        if (isDel) {
            isDel = false;
            thumbPicAdapter.setIsDel(isDel);
            thumbPicAdapter.notifyDataSetChanged();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (isDel) {
            isDel = false;
            thumbPicAdapter.setIsDel(isDel);
            thumbPicAdapter.notifyDataSetChanged();
            return;
        }
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rl_patient_user:
                ActivityUtils.showActivityForResult(this, PatientListActivity.class, REQUEST_CODE);
                break;
            case R.id.tv_add_picture:
                addPicture();
                break;
            case R.id.btn_commit:
                if (!NetUtil.isNetworkAvailable(FastInquiryActivity.this)) {
                    GetToast.useString(FastInquiryActivity.this,getResources().getString(R.string.l_loading_connect_err));
                    return ;
                }
                showTimeCountDownDialog();
                break;
            case R.id.btn_commit2:
                showToast("您的积分不足");
                break;
            case R.id.titlebar_right_view:
                ActivityUtils.showActivity(this, MyInquiryActivity.class);
                break;
        }
    }

    /**
     * 判断是否上传成功，继续上传
     */
    private void goOn() {
        count++;
        if (count < allUrls.size()) {
            upLoader.uploadImage(allUrls.get(count));
        } else {
            if (imgSuccessURLs.size() == allUrls.size()) {
                //TODO 上传成功
                Content content1 = new Content();
                content1.setMessage(etQuestionContent.getText().toString().trim());
                content1.setImages(imgSuccessURLs);
                Gson gson = new Gson();
                provider.requestFastInquiry(gson.toJson(content1), userDesc, FLAT_FAST_INQUIRY);
            }
        }
    }

    /**
     * 第一次上传和重新上传
     *
     * @param urls
     */
    private void upload(ArrayList<String> urls) {
        count = 0;
        allUrls.clear();
        allUrls.addAll(urls);
        upLoader.uploadImage(allUrls.get(count));
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (FLAT_FAST_INQUIRY.equals(actionName)) {
            //提问完毕直接跳转,后台会扣除积分
            Bundle bundle = new Bundle();
            bundle.putBoolean(MyInquiryActivity.IS_GO_BACK_MINE, true);
            ActivityUtils.showActivity(this, MyInquiryActivity.class, bundle);
            finish();
        } else if (ImageUpLoader.FLAG.equals(actionName)) {
            if (!imgSuccessURLs.contains((String) object)) {
                imgSuccessURLs.add((String) object);
            }
            goOn();
        } else if (REQUEST_MY_SCORE.equals(actionName)) {
            score = (Score) object;
            if (Integer.valueOf(score.getGradeValue()) < 10) {
                btnCommit2.setVisibility(View.VISIBLE);
                btnCommit.setVisibility(View.GONE);
            } else {
                btnCommit2.setVisibility(View.GONE);
                btnCommit.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        if (ImageUpLoader.FLAG.equals(actionName)) {
            if (!imgFailureURLs.contains(allUrls.get(count))) {
                imgFailureURLs.add(allUrls.get(count));
            }
            goOn();
        } else if (FLAT_FAST_INQUIRY.equals(actionName)) {
            if (!TextUtils.isEmpty(response)) {
                showToast(JsonUtils.getFiledData(response, "msg"));
            } else {
                showToast("请检查网络连接!");
            }
        }
    }


    private void addPicture() {
        Intent intent = new Intent(this, PhotoPickerActivity.class);
        intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, showCamera);
        intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, selectedMode);
        intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, maxNum);
        intent.putStringArrayListExtra(PhotoPickerActivity.EXTRA_SELECTED_LIST, mPhotos);
        startActivityForResult(intent, PICK_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            PatientUser patient = (PatientUser) data.getSerializableExtra("patient");
            setPatientUI(patient);
        } else {
            if (requestCode == PICK_PHOTO) {
                if (resultCode == RESULT_OK) {
                    ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);

                    gridViewImage.setVisibility(View.VISIBLE);
                    tvAddPicture.setVisibility(View.GONE);

                    //mPhotos.clear();
                    //取两个集合的去重复并集
                    result.removeAll(mPhotos);
                    mPhotos.addAll(result);
                    thumbPicAdapter = new ThumbPicAdapter(this, mPhotos);
                    gridViewImage.setAdapter(thumbPicAdapter);

                    thumbPicAdapter.setDelClickListener(new OnMyClickListener() {
                        @Override
                        public void onClick(int position, String flag) {
                            try {
                                mPhotos.remove(position);
                                thumbPicAdapter.notifyDataSetChanged();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    private void setPatientUI(PatientUser patient) {

        int gender = patient.getGender();
        String genderStr = "女";
        if (gender == 1) {
            genderStr = "男";
            ivIcon.setImageResource(R.drawable.ic_gender_male);
        } else {
            ivIcon.setImageResource(R.drawable.ic_gender_female);
        }
        int year = Integer.parseInt(patient.getBirthday().split("-")[0]);
        int age = Calendar.getInstance().get(Calendar.YEAR) - year;
        userDesc = patient.getNick() + "," + genderStr + "," + age + "岁";
        tvInquiryKey.setText("问诊人："+patient.getNick() + "," + genderStr + "," + age + "岁");
    }

    class ThumbPicAdapter extends BaseAdapter {

        private static final int TYPE_ADD = 0;
        private static final int TYPE_PHOTO = 1;
        private ArrayList<String> mDatas;
        private Context mContext;
        private int mWidth;

        private boolean isDel;

        public ThumbPicAdapter(Context context, ArrayList<String> mDatas) {
            this.mDatas = mDatas;
            this.mContext = context;
            mWidth = (ScreentUtils.getScreenWidth(context) - DensityUtil.dip2px(context, 35)) / 4;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (position == getCount() - 1 && mDatas.size() != 5) {
                return TYPE_ADD;
            } else {
                return TYPE_PHOTO;
            }
        }

        @Override
        public int getCount() {
            if (mDatas == null) {
                return 0;
            } else if (mDatas.size() < 5) {
                return mDatas.size() + 1;
            } else {
                return mDatas.size();
            }
//            return mDatas == null ? 0 : mDatas.size()+1;
        }

        @Override
        public Object getItem(int position) {
            return mDatas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (getItemViewType(position) == TYPE_ADD) {
                holder = ViewHolder.get(parent, convertView, R.layout.item_add_thumb_pic, position);
            } else {
                holder = ViewHolder.get(parent, convertView, R.layout.item_thumb_pic, position);
                SquareLayout ivThumbPic = holder.getView(R.id.iv_thumb_pic);
                ImageView ivDelPic = holder.getView(R.id.iv_delete_pic);
                if (isDel) {
                    ivDelPic.setVisibility(View.VISIBLE);
                    ivDelPic.setTag(position);
                    ivDelPic.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (listener != null) {
                                int pos = (int) v.getTag();
                                listener.onClick(pos, "");
                            }

                        }
                    });
                } else {
                    ivDelPic.setVisibility(View.GONE);
                }
                //            ImageLoader.getInstance().displayImage("file://"+mDatas.get(position), imageView, MyApplication.optionsPic);
                ImageLoader.getInstance().display(mDatas.get(position), ivThumbPic, mWidth, mWidth);
            }
            return holder.getConvertView();
        }

        public void setIsDel(boolean isDel) {
            this.isDel = isDel;
        }

        private OnMyClickListener listener;

        private void setDelClickListener(OnMyClickListener listener) {
            this.listener = listener;
        }
    }


    class Content {
        private String message;
        private List<String> images;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public List<String> getImages() {
            return images;
        }

        public void setImages(List<String> images) {
            this.images = images;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //请求一下积分
        provider.requestMyScore(REQUEST_MY_SCORE);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    AlertDialog evaluateDialog;

    private void showTimeCountDownDialog() {
        //可以只发文字，可以只发图片？
        if (TextUtils.isEmpty(userDesc)) {
            showToast("选择问诊人");
            return;
        }
        String content = etQuestionContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            showToast("说点什么吧");
            return;
        }
        if (content.length() <= 15) {
            showToast("不能少于15个字");
            return;
        }
        if (content.length() >= 200) {
            showToast("当前输入文字大于最高限制(200)，请精简语言");
            return;
        }

        Builder builder = new Builder(this);
        View v = View.inflate(this, R.layout.dialog_doctor_evaluate, null);
        ((TextView) v.findViewById(R.id.tv_title)).setText("提示");
        ((TextView) v.findViewById(R.id.tv_content)).setText("提问成功将扣除10积分");
        ((Button) v.findViewById(R.id.btn_evaluate)).setText("提问");
        //评价按钮监听
        v.findViewById(R.id.btn_evaluate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Integer.valueOf(score.getGradeValue()) < 10) {
                    showToast("积分不足10分");
                } else {
                    //提价问题
                    if (mPhotos.size() <= 0) {
                        //只发文字
                        Content content1 = new Content();
                        content1.setMessage(etQuestionContent.getText().toString().trim());
                        content1.setImages(new ArrayList<String>());
                        Gson gson = new Gson();
                        provider.requestFastInquiry(gson.toJson(content1), userDesc, FLAT_FAST_INQUIRY);
                    } else {
                        //发图片后提交文字
                        upLoader = new ImageUpLoader(FastInquiryActivity.this, FastInquiryActivity.this);
                        upload(mPhotos);
                    }
                }
                if (evaluateDialog != null) {
                    evaluateDialog.dismiss();
                }
            }
        });
        builder.setView(v);
        evaluateDialog = builder.show();
    }
}
